<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\UrlDomainModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\utils\Helper;

class UrlDomainService extends BaseModelService
{
    public static function getModel(){
        return new UrlDomainModel();
    }

    public static function edit($info){
        $id = $info['id'];
        unset($info['id']);
        if($id == 0){
            self::addUrlDomain($info);
        }
        else{
            self::updateUrlDomain($id,$info);
        }
        UrlConfigService::deleteCache();
        return $info;
    }

    public static function addUrlDomain($info){
        $type = $info['type'];
        $other = self::getByFilter(['type' => $type]);
        if(empty($other)){
            $info['is_default'] = 1;
            $info['priority'] = 0;
        }
        self::add($info);
    }

    public static function updateUrlDomain($id,$info){
        //类型不允许修改
        unset($info['type']);
        self::update($id,$info);
    }
  
    public static function setDefaultById($id){
        $origin  = self::getBase($id);
        $lastDefault = self::getByFilter([
            'is_default' => 1,
            'type' => $origin['type'],
        ]);
        if($lastDefault){
            if($lastDefault['id'] == $id){
                return 0;
            }
            self::update($lastDefault['id'],[
                'is_default' => 0,
            ]);
        }
        self::update($id,[
            'is_default' => 1,
        ]);
        UrlConfigService::deleteCache();
        return $lastDefault;
    }
   

    /**
     * 
     */
    public static function delById($id){
        $origin = self::getBase($id);
        if(empty($origin)){
            return ;
        }
        if($origin['is_default']){
            throw new ApiException("默认域名不允许删除",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $relation = UrlDomainRelationService::getByFilter(['url_domain_id' => $id]);
        if(!empty($relation)){
            throw new ApiException("域名有正在使用的映射关系.不允许删除",ErrnoPlus::COMMON_INVALID_INPUT);
        }
        $res = self::del($id);
        UrlConfigService::deleteCache();
        return $res;
    }

   

    public static function getSingleDomainInfo($selectorType){
        $config = UrlConfigService::getAllConfig();
        $infos = $config['domain'];
        $res = [];
        foreach($infos as $info){
            if($info['is_default']  == 1){
                continue;
            }
            $selectorCount = count($info['selector']);
            if($selectorCount > 1 ){
                continue;
            }
            if($selectorCount == 1 ){
                if($info['selector'][0]['type'] != $selectorType){
                    continue;
                }                
            }
            $res[] = $info;
        }
        return $res;
    }

    /**
     * 单一筛选器下的所有
     */
    public static function updateBySingle($selectorData){
        $selectorType = $selectorData['type'];
        $domainInfos = self::getSingleDomainInfo($selectorType);   
        $item = $selectorData['key'];
        $isAdd = $selectorData['id'] == 0;
        $allocTypes = ['account','appShare','burn','h5','oauth','oss','4g'];
        $res = [];
        foreach($allocTypes as $domainType) {
            $id  = $selectorData[$domainType];
            $domain = Helper::filterOne($domainInfos,['id' => $id]);
            if(empty($domain) || $domain['type'] != $domainType){
                throw new ApiException("选择的域名有误");
            }
            $domainUrl = $domain['domain'];
            $res[$domainType] = [];
            $typeDomains = Helper::filter($domainInfos,['type' => $domainType]);
            if(empty($typeDomains)){// 需要新增一个
                $res[$domainType]["addNew"] = true;
            }
            else{
                foreach($typeDomains as $tmpDomain){
                    $selectors = $tmpDomain['selector'];
                    if(count($selectors) < 1 && $tmpDomain['domain'] == $domainUrl){
                        if(!isset($res[$domainType]["addEmpty"])){
                            $res[$domainType]["addEmpty"] = [];
                        }
                        $res[$domainType]["addEmpty"][] = $tmpDomain['id'];
                    }
                    else{
                        $selector = $selectors[0];
                        if($selector['type'] !== $selectorType){
                            continue;
                        }
                        else{
                            if($tmpDomain['domain'] == $domainUrl){
                                if(!in_array($item,$selector['includes'])){ // 添加包含值
                                    if(!isset($res[$domainType]["addItem"])){
                                        $res[$domainType]["addItem"] = [];
                                    }
                                    $res[$domainType]["addItem"][] = $tmpDomain['id'];
                                }
                                else{
                                    if(!isset($res[$domainType]["already_exist"])){
                                        $res[$domainType]["already_exist"] = [];
                                    }
                                    $res[$domainType]["already_exist"][] = $tmpDomain['id'];
                                }
                            }
                            else{
                                if(in_array($item,$selector['includes'])){ // 添加包含值
                                    if(!isset($res[$domainType]["needRemoveItem"])){
                                        $res[$domainType]["needRemoveItem"] = [];
                                    }
                                    $res[$domainType]["needRemoveItem"][] = $tmpDomain['id'];
                                }
                            }
                        }
                    }
                }
                if(!isset($res[$domainType]["addEmpty"]) && !isset($res[$domainType]["addItem"]) && !isset($res[$domainType]["already_exist"])){
                    $res[$domainType]["addNew"] = true;
                }
            }
        }

    }

    public static function buildCondition($filter)
    {
        $res = [];
        if(isset($filter['name']) && !empty($filter['name'])){
            $res['name'] = ['like','%'.$filter['name'].'%'];
        }
        if(isset($filter['type']) && !empty($filter['type'])){
            $res['type'] = $filter['type'];
        } 

        if(isset($filter['domain']) && !empty($filter['domain'])){
            $res['domain'] =  ['like','%'.$filter['domain'].'%'];
        } 
        return $res;
    }

}
